package com.edu.ahm.syn;

/**
 *  synchronized 不要去锁那个 run 因为需要锁的 是 账户
 */
public class SafeBank {

    public static void main(String[] args) {
        Account account = new Account(1000000,"61252213234ahm");

        Bank2 bank1 = new Bank2(account, 100000, "太原分行");
        Bank2 bank2 = new Bank2(account, 1000000, "吕梁分行");

        bank1.start();
        bank2.start();
    }
}

class Account2{
    int money; // 余额
    String accountNum; // 卡号

    public Account2(int money,String accountNum){
        this.money = money;
        this.accountNum = accountNum;
    }
}

// 银行模拟取款
class  Bank2 extends Thread{
    Account account;
    int getMoney;

    public Bank2(Account account,int getMoney, String name){
        super(name);
        this.account = account;
        this.getMoney = getMoney;
    }
    @Override
    public  void run() {
        synchronized (account){
            // 判断如果取得钱不够了
            if (getMoney>account.money){
                System.out.println(Thread.currentThread().getName()+"钱不够，去不了");
                return;
            }
            try {
                // 模拟办理延时
                this.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.money -=getMoney;
            System.out.println(account.accountNum+"的余额为:"+account.money);
        }
    }
}